package com.example.demo3.listener;

import cn.hutool.core.util.ObjectUtil;
import lombok.extern.slf4j.Slf4j;
import org.flowable.common.engine.api.delegate.event.FlowableEngineEntityEvent;
import org.flowable.engine.FormService;
import org.flowable.engine.ProcessEngine;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.TaskService;
import org.flowable.engine.delegate.event.AbstractFlowableEngineEventListener;
import org.flowable.engine.form.FormProperty;
import org.flowable.engine.form.TaskFormData;
import org.flowable.task.service.impl.persistence.entity.TaskEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
@Slf4j
public class GlobalEventListener extends AbstractFlowableEngineEventListener {
    @Autowired
    TaskService taskService;
    @Autowired
    FormService formService;
    @Autowired
    RuntimeService runtimeService;
    @Autowired
    ProcessEngine processEngine;

    /**
     * 流程结束监听器
     */
    @Override
    protected void processCompleted(FlowableEngineEntityEvent event) {
        System.out.println("processCompleted");
    }

    @Override
    protected void taskCreated(FlowableEngineEntityEvent flowableEngineEvent) {
        System.out.println("taskCreated");
        Map<String, Object> variables = new HashMap<>();
        variables.put("approved", true);
//        int label = 0;
//        variables.put("label", label);
        TaskEntity entity = (TaskEntity) flowableEngineEvent.getEntity();
//        TaskFormData taskFormData = formService.getTaskFormData(entity.getId());
//        StrategyRunForm strategyRunForm = runtimeService.getVariable(entity.getExecutionId(), "strategyRunForm", StrategyRunForm.class);
//        entity.getTaskDefinitionKey();
//        String split = entity.getTaskDefinitionKey().split("_")[1];
//        runtimeService.deleteProcessInstance(entity.getProcessInstanceId(), "流程结束");

//        TaskFormData taskFormData = processEngine.getFormService().getTaskFormData(entity.getId());
//        List<FormProperty> formProperties = taskFormData.getFormProperties();

        if (ObjectUtil.equals(entity.getFormKey(), "label")) {
            Object objLabel = entity.getVariable("labelList");
            List<Integer> labelList = new ArrayList<>();
            if (ObjectUtil.isEmpty(objLabel)) {
                labelList.add(1);
            } else {
                labelList = (List<Integer>) objLabel;
                labelList.add(0);
            }
            runtimeService.setVariable(entity.getProcessInstanceId(), "labelList", labelList);

        }
        taskService.complete(entity.getId(), variables);
    }
}
